/*
 * @Author: xixi
 * @Date: 2020-03-05 14:35:33
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-03-06 17:27:05
 * @Description: 留言板，能编写留言，并且发布显示在页面上
 * @FilePath: /react/node-study/feedback/app.js
 */

/**
 * 约定：
 *      1、引包写在代码最上面
 *      2、将html文件放在views中
 */

 let http = require('http')
 let fs = require('fs')
 let template = require('art-template')
 let url = require('url')

 let comments = [
    {name:'张三',msg:'今天天气不错',dateTime:'2020-03-07'},
    {name:'张三1',msg:'今天天气',dateTime:'2020-03-08'},
    {name:'张三2',msg:'今天',dateTime:'2020-03-09'},
    {name:'张三3',msg:'天气不错',dateTime:'2020-04-06'},
    {name:'张三4',msg:'不错',dateTime:'2020-03-06'},
 ]
    
 

 http
    .createServer((req,res) => {
        // let url = req.url
        let parseObj = url.parse(req.url,true)
        let pathname = parseObj.pathname
        if(pathname === '/'){
            fs.readFile('./views/index.html',(err,data) => {
                if(err) return res.end('err')
                var str = template.render(data.toString(),{
                    comments:comments
                })
                res.end(str)
            })
        }else if(pathname === '/post'){
            fs.readFile('./views/post.html',(err,data) => {
                if(err) return res.end('err')
                res.end(data)
            })
        }else if(pathname === '/pinglun'){
            let paramObj = parseObj.query
            paramObj.dateTime = '2020-03-06'
            comments.unshift(paramObj)
            res.statusCode = 302       //通过服务器让客户端重定向，状态码设置为302
            res.setHeader('location','/')   //location代表重定向的位置，后面的参数代表重定向的位置
            res.end()
        }else if(pathname.indexOf('/public/') === 0){
                //这是用于页面的请求数据，将其变为文件数据
            fs.readFile('.'+pathname,(err,data) => {
                if(err) return res.end('err')
                res.end(data)
            })
        }else{
            fs.readFile('./views/404.html',(err,data) => {
                if(err) return res.end('err')
                res.end(data)
            })
        }
    })
    .listen(3000,() => {
        console.log('start--------------------------------------')
    })

 